﻿<?php
session_start();

include('database.php');
include("language.php");

$_SESSION['curPage'] = 'login.php';

$error = '';

if(isset($_SESSION['connected']) AND $_SESSION['connected'])
{
    header("Location: home.php");
}
else 
{
    if(isset($_POST['username']) AND isset($_POST['password']))
    {
        try
        {
            $query = $db->prepare("SELECT * FROM user WHERE username = ?");
            $query->execute(array($_POST['username']));


            if($query->rowCount() == 0)
            {
                $error = $login_usernameDoesntExist;
            }
            else
            {
                $data = $query->fetch();
                
                $password = md5($_POST['password'] . $data['salt']);
                
                if($password <> $data['password'])
                {
                    $error = $login_incorrectPassword;
                }
                else 
                {
                    $_SESSION['connected'] = true;
                    $_SESSION['username'] = $_POST['username'];
                    $_SESSION['id'] = $data['id'];
                    $_SESSION['access'] = $data['access'];
                    header("Location: home.php");
                }
            }
            $query->closeCursor();
        }
        catch (Exception $e)
        {
            die('ERROR : ' . $e->getMessage());
        }

    }
}

?>

<!DOCTYPE html>
<html>
    <head>
        <title><?php echo $login_connection; ?></title>
        <meta charset="utf-8" />
            <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <div class="d_body">
            <?php include("header.php"); ?>
            <?php include("menuBar.php"); ?>

            <h1><?php echo $login_connection; ?></h1>

            <form method="post" action="login.php">
                <?php
                if(strlen($error) <> 0)
                {
                    echo '<p class="text_error">' . $error . '</p><br>';
                }
                ?>
                <table class="drawTable">
                    <tr>
                        <td><label><?php echo $register_username; ?></label></td>
                        <td><input name="username" type="text" /></td>
                    </tr>

                    <tr>
                        <td><label><?php echo $register_password; ?></label></td>
                        <td><input name="password" type="password" /></td>
                    </tr>
                    <tr>
                        <td class="cellTextCenter" colspan="2"><input type="submit" value="<?php echo $menuBar_login; ?>" /></td>
                    </tr>
                </table>
                
            </form>

            <p><?php echo $login_noAccountYet; ?> <a href="register.php"><?php echo $login_subscribe; ?></a> <?php echo $login_inLessThanAMinute; ?></p>
        </div>
        <?php include('footer.php'); ?>
    </body>
</html>